<?php
/**
 */
class Yz_Action_Select
    extends Yz_Action_Abstract
    implements Yz_Action_Interface
{


    /************************************
     *          Public methods          *
     ************************************/

    /** @see Yz_Action_Interface::assignFields()
     *  @param string|hash
     *  @return chainable
     */
    public function assignFields( $fields )
    {
        if ('*' === $fields) {
            $fields = array('*');
        } else {
            $fields = new Yz_Hash($fields);
            if ($fields->isEmpty()) {
                throw new Yz_Exception("Fields can not be empty");
            }
            $this->fields = $this->identifyFields($fields);
        }
        return $this;
    }

    /**
     *  @return chainable
     */
    public function execute()
    {
        debug();
        $this->statement = $this
            ->buildSelect()
            ->execute();
        return $this;
    }

    /**
     *  @return Yz_Hash
     */
    public function fetch()
    {
        return $this->getStatement()->fetch();
    }



    /************************************
     *        Protected methods         *
     ************************************/


    /**
     *  Common SELECT statement creator
     *  @return Yz_SQL_Statement_Select
     */
    protected function buildSelect()
    {
        debug();
        $tables = $this->tableList;
        $fields = $this->fields;
        $sql = \Yz_SQL_Statement_Select::create()
            ->select($fields)
            ->from($tables->current(), $tables->key());
        if (count($tables) > 1) {
            $sql->join($tables->slice(1));
        }
        return $sql;
    }


}
